<?php


namespace SidToken\Model;


use Think\Model;

class SidUserMinerModel extends Model
{
    const STATUS_ON = 1;
    const STATUS_DELETE = -1;
    const STATUS_OFF = 0;

    const TYPE_BUY = 'buy';
    const TYPE_REWARD = 'reward';

    public function userCanBuyAmount($uid, $minerId)
    {
        $MinerModel = new SidMinerModel();
        $miner = $MinerModel->field("limit_amount,left_amount")->where(['id' => $minerId])->find();
        $minerLimitAmount = 0;
        if ($miner != null) {
            $minerLimitAmount = $miner['limit_amount'] > $miner['left_amount'] ? $miner['left_amount'] : $miner['limit_amount'];
        }
        $userHasAmount = $this->where(['miner_id' => $minerId, "uid" => $uid])->count();
        return $minerLimitAmount - $userHasAmount;
    }

    public function statusString($status, $startTime)
    {
        if ($status == self::STATUS_ON) {
            if ($startTime > time()) {
                return "待生产";
            } else {
                return "运行中";
            }

        } else if ($status == self::STATUS_DELETE) {
            return "已删除";
        } else if ($status == self::STATUS_OFF) {
            return "已关闭";
        } else {
            return "ERROR";
        }
    }

    public function rewardMiner($minerId, $minerName, $minerDayAmount, $minerReleaseDay, $limitAmount, $uid)
    {
        if ($limitAmount < 10) {
            return;
        }

        $countBuy = $this->where(['miner_id' => $minerId, 'uid' => $uid, 'type' => self::TYPE_BUY])->count();
        $countReward = $this->where(['miner_id' => $minerId, 'uid' => $uid, 'type' => self::TYPE_REWARD])->count();

        if ($countBuy % 10 == 0 && $countBuy > 0) {
            $shouldReward = $countBuy / 10;
            $miners = [];
            if ($countReward < $shouldReward) {
                $rewardAmount = $shouldReward - $countReward;
                while ($rewardAmount > 0) {
                    $data = [
                        'uid' => $uid,
                        'order_sn' => time() . mt_rand(1000, 9999),
                        'name' => "[赠送]" . $minerName,
                        'total_get_amount' => $minerDayAmount * $minerReleaseDay,
                        'start_time' => strtotime(date('Ymd')) + 86400,
                        'create_time' => time(),
                        'end_time' => strtotime(date('Ymd')) + 86400 + 86400 * $minerReleaseDay,
                        'day_amount' => $minerDayAmount,
                        'miner_id' => $minerId,
                        'status' => self::STATUS_ON,
                        'type' => self::TYPE_REWARD
                    ];
                    $miners[] = $data;
                    //$this->add($data);
                    $rewardAmount--;
                }
                $this->addAll($miners);
            }
        }
    }

}